#!/bin/bash
#这里可替换为你自己的执行程序，其他代码无需更改
APP_NAME=server-fast.jar
WORKDIR=/opt/java/server-fast

#使用说明，用来提示输入参数
usage() {
 echo "Usage: sh 脚本名.sh [start|stop|restart|status]"
 exit 1
}

#启动方法
start(){
 pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v /opt/java/fq-server|awk '{print $2}' `
 if [ ${pid} ]; then
 echo "${APP_NAME} is already running. pid=${pid} ."
 else
 nohup java -Xms256m -Xmx512m -XX:MaxPermSize=512m -Dfile.encoding=UTF-8 -jar $WORKDIR/$APP_NAME --spring.config.location="$WORKDIR/application.yml" > /dev/null 2>&1 &
 sleep 1
 pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v /opt/java/fq-server|awk '{print $2}' `
 echo "${APP_NAME} start success. pid = ${pid}"
 fi
}

#停止方法
stop(){
 pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v /opt/java/fq-server|awk '{print $2}' `
 if [ ${pid} ]; then
   kill -15 $pid
 fi

 while [ ${pid} ]
 do
  echo "${APP_NAME} is currently being closed with PID ${pid}. Please wait for the closure to complete"
  sleep 1
  pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v /opt/java/fq-server|awk '{print $2}' `
 done
 echo "${APP_NAME} is not running"
}

#输出运行状态
status(){
 pid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v /opt/java/fq-server|awk '{print $2}' `
 if [ ${pid} ]; then
 echo "${APP_NAME} is running. Pid is ${pid}"
 else
 echo "${APP_NAME} is NOT running."
 fi
}

#重启
restart(){
 stop
 start
 status
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
 "start") start ;;
 "stop")  stop ;;
 "status") status ;;
 "restart") restart ;;
 *)
 usage;;
esac
